<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name"
                placeholder="输入查询名称"
                style="width: 200px; margin-right: 20px;"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-button v-waves
                 class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 size="small"
                 @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 size="small"
                 icon="el-icon-plus"
                 @click="handleCreate">
        新建
      </el-button>
    </div>
    </br>
    <!--包配置列表    -->
    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              style="width: 100%;"
              @sort-change="sortChange">
      <el-table-column type="index"
                       align="center"
                       label="#" />
      <el-table-column label="名称"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="父包"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.parent }} </span>
        </template>
      </el-table-column>
      <el-table-column label="模块名"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.moduleName }} </span>
        </template>
      </el-table-column>
      <el-table-column label="Controller"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.controller }}</span>
        </template>
      </el-table-column>

      <el-table-column label="Service"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.service }}</span>
        </template>
      </el-table-column>

      <el-table-column label="Service Impl"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.serviceImpl }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Entity"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.entity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Mapper接口"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.mapper }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Mapper XML"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.xml }}</span>
        </template>
      </el-table-column>

      <el-table-column label="Pojo"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.other }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       width="200px"
                       class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary"
                     size="mini"
                     @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'"
                     size="mini"
                     type="danger"
                     @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="listQuery.pageNo"
                :limit.sync="listQuery.pageSize"
                @pagination="getList" />
    <!--编辑和新增的表单 -->
    <el-dialog :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="left"
               label-width="140px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="名称"
                      prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="父包"
                      prop="parent">
          <el-input v-model="temp.parent" />
        </el-form-item>
        <el-form-item label="模块名"
                      prop="moduleName">
          <el-input v-model="temp.moduleName" />
        </el-form-item>
        <el-form-item label="Controller"
                      prop="controller">
          <el-input v-model="temp.controller" />
        </el-form-item>
        <el-form-item label="Entity"
                      prop="entity">
          <el-input v-model="temp.entity" />
        </el-form-item>
        <el-form-item label="Service"
                      prop="service">
          <el-input v-model="temp.service" />
        </el-form-item>
        <el-form-item label="Service Impl"
                      prop="serviceImpl">
          <el-input v-model="temp.serviceImpl" />
        </el-form-item>
        <el-form-item label="Mapper"
                      prop="mapper">
          <el-input v-model="temp.mapper" />
        </el-form-item>
        <el-form-item label="Mapper XML"
                      prop="xml">
          <el-input v-model="temp.xml" />
        </el-form-item>
        <el-form-item label="Pojo"
                      prop="other">
          <el-input v-model="temp.other" />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary"
                   @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible"
               title="Reading statistics">
      <el-table :data="pvData"
                border
                fit
                highlight-current-row
                style="width: 100%">
        <el-table-column prop="key"
                         label="Channel" />
        <el-table-column prop="pv"
                         label="Pv" />
      </el-table>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import { page, saveOrUpdate, remove } from '@/api/package'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'mysql', display_name: 'mysql' },
  { key: 'oracle', display_name: 'oracle' },
  { key: 'postgresql', display_name: 'postgresql' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter (type) {
      return calendarTypeKeyValue[type]
    }
  },
  data () {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageSize: 10,
        pageNo: 1,
        dbTypeName: undefined,
        name: undefined
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        parent: 'com.pearl',
        controller: 'controller',
        moduleName: '',
        entity: 'entity',
        service: 'service',
        serviceImpl: 'service.impl',
        mapper: 'mapper',
        xml: 'xml',
        other: 'api.pojo',
        pathInfo: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        // type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
          moduleName: [{ required: true, message: '模块名称不能为空', trigger: 'blur' }],
        parent: [{ required: true, message: '父包名不能为空', trigger: 'blur' }],
        entity: [{ required: true, message: 'Entity 包名不能为空', trigger: 'blur' }],
        service: [{ required: true, message: 'Service 包名不能为空', trigger: 'blur' }],
        serviceImpl: [{ required: true, message: 'Service Impl 包名不能为空', trigger: 'blur' }],
        mapper: [{ required: true, message: 'Mapper 包名不能为空', trigger: 'blur' }],
        xml: [{ required: true, message: 'Mapper XML 包名不能为空', trigger: 'blur' }],
        controller: [{ required: true, message: 'Controller 包名不能为空', trigger: 'blur' }],
          other: [{ required: true, message: 'Pojo 包名不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },
    handleFilter () {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus (row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange (data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID (order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp () {
      this.temp = {
          id: undefined,
          name: '',
          parent: 'com.pearl',
          controller: 'controller',
          moduleName: '',
          entity: 'entity',
          service: 'service',
          serviceImpl: 'service.impl',
          mapper: 'mapper',
          xml: 'xml',
          other: 'api.pojo',
          pathInfo: ''
      }
    },
    // 处理新增确定
    handleCreate () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveOrUpdate(this.temp).then(() => {
            page(this.listQuery).then(response => {
              this.list = response.data
              this.total = response.total
            })
            this.dialogFormVisible = false
            this.$notify({
              title: '提示信息',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate (row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    updateData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          saveOrUpdate(tempData).then(() => {
            page(this.listQuery).then(response => {
              this.list = response.data
              this.total = response.total
            })
            this.dialogFormVisible = false
            this.$notify({
              title: '提示信息',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除
    handleDelete (row, index) {
      remove(row.id).then(() => {
        page(this.listQuery).then(response => {
          this.list = response.data
          this.total = response.total
        })
        this.$notify({
          title: '提示信息',
          message: '成功删除',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleFetchPv (pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },

    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
